package com.txc.cloud.gateway.filters;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.txc.cloud.gateway.config.AuthExcludeProperties;
import com.txc.common.global.model.LoginUser;
import com.txc.common.global.model.UserPermission;
import com.txc.common.global.result.Result;
import com.txc.common.global.result.ResultCode;
import com.txc.common.utils.format.ObjectFormat;
import com.txc.common.utils.jwt.TokenManager;
import com.txc.common.utils.middleware.RedisUtils;
import com.txc.common.utils.supply.ServerHttpResponseUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import jakarta.annotation.Resource;
import java.util.List;

import static com.txc.common.global.constant.NumConstant.*;
import static com.txc.common.global.constant.StrConstant.*;

/**
 * 权限校验过滤器
 *
 * @ClassName: GlobalFilter
 * @Author: TXC
 * @Date: 2023-07-28 15:35
 **/
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private AuthExcludeProperties authExcludeProperties;
    @Resource
    private TokenManager tokenManager;
    @Resource
    private RedisUtils redisUtils;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        List<String> headers = request.getHeaders().get(AUTHORIZATION);
        String token = null;
        if (ObjectUtil.isNotNull(headers)) {
            token = headers.get(0);
        }
        ServerHttpResponse response = exchange.getResponse();
        try {
            if (StrUtil.isBlank(token)) {
                return ServerHttpResponseUtil.out(response, Result.fail(ResultCode.USER_NOT_LOGIN));
            }
            String userId = tokenManager.getUserId(token);
            if (!authorisation(request, userId)) {
                return ServerHttpResponseUtil.out(response, Result.fail(ResultCode.NO_PERMISSION));
            }
        } catch (Exception e) {
            return ServerHttpResponseUtil.out(response, Result.fail(ResultCode.USER_ACCOUNT_EXPIRED));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

    /**
     * 排除路径
     *
     * @param path 路径
     * @return 是否排除
     * @author TXC
     */
    private boolean isExclude(String path) {
        for (String excludePath : authExcludeProperties.getExcludes()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    private boolean authorisation(ServerHttpRequest request, String userId) {
        LoginUser user = ObjectFormat.objToObject(redisUtils.get(tokenManager.getCacheKey() + userId), LoginUser.class);
        String path = request.getURI().getPath();
        if (ObjectUtil.isNotNull(user)) {
            if (path.startsWith(SLASH)) {
                path = path.substring(ONE);
            }
            String permissionsCode = path.replace(SLASH, COLON);
            UserPermission userPermission = user.getPermissions().getOrDefault(permissionsCode, null);
            if (ObjectUtil.isNotNull(userPermission) && !userPermission.isHasPermission()) {
                return false;
            }
            request.mutate().headers(httpHeaders -> {
                httpHeaders.add(PERMISSIONS_CODE, permissionsCode);
            });
            return true;
        }
        return false;
    }
}
